<script>
import dayjs from "dayjs";
import rayMulImageUpload from '@/RayComponents/rayMulImageUpload.vue'
// import receivedAmountUpload from './receivedAmountUpload.vue';
import quinn from "@/utils/quinn";
import print from 'print-js'
import Decimal from 'decimal.js';
import axios from 'axios';
import _ from 'lodash';
export default {
    components: {
        rayMulImageUpload,
        // receivedAmountUpload,
    },
    mounted() {
        // this.materialData = this.material;
        this.getWarehouse();
        // this.clipData();
        document.addEventListener('paste', this.handlePaste)
        const { userName = [] } =
  quinn.getStorage("userDatav3") || store.state.userData || {};
  this.userName = userName;
    },
    props: {
        statusType: {
            type: String,
            default: ''
        },
        materials: {
            type: Object, Array,
            default: (() => { })
        },
        fileType: {
            type: String,
            default: 'IMAGE'
        },
        timer: {
            type: Number,
            default: 0
        }


    },
    watch: {
        // timer:{
        //     handler(newVal) {
        //         this.closeSend();
        //     },
        //     deep: true,
        //     immediate: true
        // },
        materials: {
            handler(newVal, oldVal) {
                if (this.statusType != '导入报货单') {
                    this.saleInfo.receivedAmount = newVal.receivedAmount;
                    this.materialData = newVal.materials;
                    this.saleInfo.storeAddress = newVal.storeAddress;
                    this.saleInfo.storeContacts = newVal.storeContacts;
                    this.saleInfo.storeName = newVal.storeName;
                    this.saleInfo.warehouseId = newVal.warehouseId;
                    this.saleId = newVal.saleId
                    this.saleInfo.saleTime = newVal.saleTime;
                    if(newVal.paymentVouchers){
                        newVal.paymentVouchers.map(el => {
                        this.clipList = this.clipList.concat(this.host + el)
                    })
                    }
                    this.saleInfo.remark = newVal.remark;

                    if (newVal.outVouchers) {
                        newVal.outVouchers.map(el => {
                            if (el != '') {
                                this.outVouchersList = this.outVouchersList.concat(this.host + el);
                            }

                        })
                    }



                }
            },
            deep: true,
            immediate: true
        },
        materialData: {
            handler(newVal) {
                this.allPrice = new Decimal(0);
                this.materialData = newVal;
                if (this.statusType != '导入报货单') {
                    this.materialData.map(el => {
                        this.allPrice = Decimal(this.allPrice).plus(Decimal(el.salePrice).mul(Decimal(el.count)));
                    })
                } else {
                    this.materialData.map(el => {
                        this.allPrice = Decimal(this.allPrice).plus(Decimal(el.salePrice).mul(Decimal(el.count)));
                    })
                }


            },
            deep: true,
            immediate: true
        },
        statusType: {
            handler(newVal) {
                this.statusType = newVal;
            },
            deep: true,
            immediate: true
        }
    },
    data() {
        return {
            accept: '.xls,.XLS,.xlsx,.XLSX',
            warehouseList: [],
            userName:'',
            // warehouseId: '',
            outIn: {
                outVouchers: ''
            },
            printStatus:false,
            host: this.$imgHost,
            saleId: 0,
            saleInfo: {
                storeContacts: '',
                storeAddress: '',
                storeName: '',
                receivedAmount: '',
                receivedVouchers: '',
                remark: '',
                saleTime: '',
                warehouseId: '',
            },
            imgList: [],
            allPrice: 0,
            allCount: 0,
            payAmountPrice: '',
            clipboardrList: [],
            clipList: [], //回款凭证
            outVouchersList: [],//出库凭证
            materialData: [],
            data: {

            },
            maxHeight:'300px'
        }
    },
    methods: {

        handlePaste(event) {
            if (this.statusType !== '导入报货单') return;

            const clipboardData = event.clipboardData || window.clipboardData;
            if (clipboardData) {
                for (let i = 0; i < clipboardData.items.length; i++) {
                    const item = clipboardData.items[i];

                    if (item.kind === 'file' && item.type.startsWith('image/')) {
                        const file = item.getAsFile();
                        if (file) {
                            this.uploadImage(file);
                        }
                    } else {
                        this.$message.error('请拷贝图片!');
                        break;
                    }
                }
            }
        },
        uploadImage(imageFile) {
            const formData = new FormData();
            formData.append('file', imageFile);
            axios.post(`${this.$apiHost}/common/upload`, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'token': window.$quinn.getStorage("tokenv3")
                }
            })
                .then(response => {
                    this.clipboardrList.push(response.data.data)
                    this.saleInfo.receivedVouchers = this.clipboardrList.join(',');

                })
                .catch(error => {
                    console.error('Upload failed:', error);
                });
        },
        printData() {
            this.printStatus = true;
            setTimeout(()=>{
                print({
                printable: 'printContainer',
                type: 'html',
                scanStyles: false,
                style: '@page { size: landscape; }',
                targetStyles: ['*']
            })
            this.printStatus  = false;
            },100)

        },
        closeSend() {
            this.$emit('close', false)
            this.materialData = []
            this.imgList = []
            this.saleInfo.storeName = ''
            this.saleInfo.storeContacts = ''
            this.saleInfo.saleTime = ''
            this.saleInfo.storeAddress = ''
            this.saleInfo.receivedAmount = ''
            this.saleInfo.receivedVouchers = ''
            this.saleInfo.warehouseId = ''
            this.saleInfo.remark = ''
            this.allPrice = 0
            this.clipList = [];
            this.clipboardrList = [];
            this.outVouchersList = []
        },
        getImage(info) {
            this.imgList.push(info);
            if (this.statusType == '出库') {
                this.outIn.outVouchers = this.imgList.join(',');
            }
        },
        getWarehouse() {
            this.$api.warehouseWarehousePullDownList().then(res => {
                this.warehouseList = res;
            })
        },
        // receivedImg(e) {
        //     this.saleInfo.receivedVouchers = e.join(',')
        // },
        inOutFunc: _.throttle(function(){
            let params = {
                    targetId: this.saleId,
                    outVouchers: this.outIn.outVouchers,
                    type: 'sale'
                }
                this.$api.inOutOut(params).then(res => {
                    this.closeSend()
                })
        },20000),
        confirm() {
            if (this.statusType == '出库') {
                this.inOutFunc();
            }
            if (this.statusType == '导入报货单') {
                if (this.materialData.length == 0) {
                    this.$message.error('材料不能为空!');
                    return;
                }
                if (this.saleInfo.warehouseId == '') {
                    this.$message.error('请选择出库仓库!');
                    return;
                }
                // for (let k in this.saleInfo) {
                //     if (this.saleInfo[k] == '' || this.materialData.length == 0 || this.warehouseId == '') {
                //         this.$message.error('请检查信息!');
                //         return;
                //     }
                // }
                if (this.saleInfo.receivedVouchers == '') {
                    this.$message.error('请上传付款凭证!');
                    return;
                }
                let countStatus = true;
                for (let i = 0; i < this.materialData.length; i++) {
                    if (Number(this.materialData[i].kccount) < Number(this.materialData[i].count)) {
                        countStatus = false;
                        this.$message.error('请检查库存');
                        break;
                    }
                }
                if (countStatus) {
                    let materData = [];
                    this.materialData.map(el => {
                        materData.push({ 'id': el.materialId, 'count': el.count })
                    })
                    let params = {
                        storeName: this.saleInfo.storeName,
                        storeContacts: this.saleInfo.storeContacts,
                        storeAddress: this.saleInfo.storeAddress,
                        materialList: materData,
                        receivedAmount: this.saleInfo.receivedAmount,
                        paymentVouchers: this.saleInfo.receivedVouchers,
                        warehouseId: this.saleInfo.warehouseId,
                        remark: this.saleInfo.remark,
                        paymentAmount: Number(this.allPrice),
                        saleTime: this.saleInfo.saleTime,
                        saleType:1,
                        wechatSaleId:'PC',
                    }
                    this.$api.saleSaleAdd(params).then(res => {
                        this.closeSend()
                    })
                }
            }


        },
        buyTimeFunc() {
            this.saleInfo.saleTime = dayjs(this.saleInfo.saleTime).format("YYYY-MM-DD");
        },
        materialListDetail(e) {
            if (e) {
                this.saleInfo.storeName = e.storeName
                this.saleInfo.storeAddress = e.storeAddress
                this.saleInfo.storeContacts = e.storeContacts
                this.allPrice = 0;
                e.materials.map(el => {
                    el.kccount = 0
                    if (el.inventories.length > 1) {
                        el.inventories.map(k => {
                            el.kccount += k.count;
                        })
                    } else if (el.inventories.length == 1) {
                        el.kccount = el.inventories[0].count;
                    }

                })
                this.materialData = e.materials;

                this.allPrice = new Decimal(0);
            } else {
                this.$message.error('报货单错误,请检查后重新尝试!');
                this.saleInfo.storeName = ''
                this.saleInfo.storeAddress = ''
                this.saleInfo.storeContacts = ''
                this.saleInfo.receivedAmount = ''
                this.saleInfo.warehouseId = ''
                this.saleInfo.saleTime = ''
                this.materialData = [];
            }

        }
    }
}
</script>
<template>
    <div>
        <div v-if="statusType == '导入报货单'" style="margin-bottom: 30px;">
            <div>请上传表格</div>
            <rayMulImageUpload :warehouseId="saleInfo.warehouseId" :data="data" @materialListDetail="materialListDetail"
                :fileType='fileType' :accept="accept" align="center"></rayMulImageUpload>
        </div>
        <div class="inputValue">
            <div>
                <div>门店名称 <span style="color: red;">*</span></div>
                <el-input placeholder='请输入门店名称'
                    :disabled="statusType == '查看明细' || statusType == '导入付款凭证' || statusType == '出库'"
                    v-model="saleInfo.storeName"></el-input>
            </div>
            <div>
                <div>配送地址 <span style="color: red;">*</span></div>
                <el-input placeholder='请输入配送地址'
                    :disabled="statusType == '查看明细' || statusType == '导入付款凭证' || statusType == '出库'"
                    v-model="saleInfo.storeAddress"></el-input>
            </div>
            <div>
                <div>配送联系人 <span style="color: red;">*</span></div>
                <el-input placeholder='请输入手机号'
                    :disabled="statusType == '查看明细' || statusType == '导入付款凭证' || statusType == '出库'"
                    v-model="saleInfo.storeContacts"></el-input>
            </div>
            <div>
                <div>出货仓库(导入报货单前 请先选择出货仓库)<span style="color: red;">*</span></div>
                <el-select :disabled="statusType == '查看明细' || statusType == '导入付款凭证' || statusType == '出库'"
                    v-model="saleInfo.warehouseId" style="width:100%" placeholder="请选择出货仓库">
                    <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName"
                        :value="item.warehouseId">
                    </el-option>
                </el-select>
            </div>
            <div>
                <div>报货时间 <span style="color: red;">*</span></div>
                <el-date-picker style="width: 100%;" @change="buyTimeFunc" v-model="saleInfo.saleTime" type="date"
                    :disabled="statusType == '查看明细' || statusType == '导入付款凭证' || statusType == '出库'" placeholder="选择日期">
                </el-date-picker>
                <!-- <el-input placeholder='请输入报货时间'
                    :disabled="statusType == '查看明细' || statusType == '导入付款凭证' || statusType == '出库'"
                    v-model="saleInfo.saleTime"></el-input> -->
            </div>
            <div  v-if="!['GD','GX'].includes(userName)">
                <div>回款金额 <span style="color: red;">*</span></div>
                <el-input type="number" clearable placeholder='请输入回款金额'
                    :disabled="statusType == '查看明细' || statusType == '导入付款凭证' || statusType == '出库'"
                    v-model="saleInfo.receivedAmount"></el-input>
            </div>
            <div>
                <div>备注 <span style="color: red;">*</span></div>
                <el-input placeholder='请输入备注'
                    :disabled="statusType == '查看明细' || statusType == '导入付款凭证' || statusType == '出库'"
                    v-model="saleInfo.remark"></el-input>
            </div>
            <div  v-if="!['GD','GX'].includes(userName)">
                <div v-if="statusType == '查看明细' || statusType == '出库'">
                <div>付款凭证<span style="color: red;">*</span></div>

                <el-image :src="v" ref="preview" v-for="(v, i) in clipList" :key="i" :preview-src-list="clipList"
                    style="width: 50px;height: 50px;" />
            </div>
            <div v-else>
                <div>付款凭证<span style="color: red;">*</span></div>

                <el-image :src="host + v" ref="preview" v-for="(v, i) in clipboardrList" :key="i"
                    :preview-src-list="clipboardrList" style="width: 50px;height: 50px;" />

            </div>
        </div>

            <div v-if="statusType == '查看明细'">
                <div>出库凭证<span style="color: red;">*</span></div>
                <el-image :src="v" ref="preview" v-for="(v, i) in outVouchersList" :key="i"
                    :preview-src-list="outVouchersList" style="width: 50px;height: 50px;" />

            </div>
            <!-- <receivedAmountUpload @url="receivedImg" v-if="statusType == '导入报货单'" /> -->
        </div>

        <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom:10px">
            <div>材料明细</div>
            <el-button type="primary" size="mini" @click='printData'>打印</el-button>
        </div>
        <div id='printContainer'>
            <div v-if="printStatus">
                <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;门店名称:{{saleInfo.storeName}} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-</span>
                <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;门店地址:{{saleInfo.storeAddress}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                <span>联系人:{{saleInfo.storeContacts}}</span>
            </div>
            <el-table :data="materialData" v-if="materialData" stripe tooltip-effect="dark" border style="width: 100%;"
           :maxHeight="printStatus ? '100%': '300px'" :headerCellStyle="{
            'background': '#303e9d',
            'textAlign': 'center',
            'color': 'white'
        }" :cellStyle="{ 'textAlign': 'center', 'fontSize': '12px' }">
         <el-table-column label="材料编码" prop="materialId" min-width="180px"></el-table-column>
        <el-table-column label="材料名称" prop="materialName" min-width="180px"></el-table-column>
            <el-table-column label="数量" prop="count"></el-table-column>
            <el-table-column label="颜色" prop="color"></el-table-column>
            <el-table-column label="规格" prop="norm"></el-table-column>
            <!-- <el-table-column label="成本价" prop="price"></el-table-column> -->
            <el-table-column label="销售价" prop="salePrice" v-if="!printStatus && !['GD','GX'].includes(userName)"  ></el-table-column>
            <el-table-column label="单位" prop="unit" ></el-table-column>
            <el-table-column label="小计"  v-if="!printStatus &&  !['GD','GX'].includes(userName)">
                <template slot-scope="scope">
                    {{ scope.row.salePrice * 100 * scope.row.count / 100 }}
                </template>
            </el-table-column>
            <el-table-column label="库存" prop="kccount" v-if="statusType == '导入报货单'">
            </el-table-column>
            <el-table-column label="库存状态" v-if="statusType == '导入报货单'">
                <template slot-scope="scope">
                    <el-link v-if='Number(scope.row.kccount) < Number(scope.row.count)' type="danger">库存不足</el-link>
                    <el-link v-else type="success">库存正常</el-link>
                </template>
            </el-table-column>
        </el-table>
        </div>
        <div class="flex" style='margin-top: 10px;' v-if="!['GD','GX'].includes(userName)" >
            <span style="color:red">*</span> <span style="margin-left: 5px;margin-right: 10px;">合计金额</span><span>{{
            allPrice
        }}</span>
        </div>
        <rayMulImageUpload :fileType='fileType' v-if="statusType == '出库'" @imageList="getImage"></rayMulImageUpload>
        <rayMulImageUpload :fileType='fileType' v-if="statusType == '导入付款凭证'" @imageList="getImage"></rayMulImageUpload>
        <el-input style='margin-top:20px' v-model.trim="payAmountPrice" v-if='statusType == "导入付款凭证"'
            placeholder="请输入回款金额"></el-input>
        <span slot="footer" style="margin-top:20px;" class="dialog-footer">
            <el-button style="background-color: white;color:#000" @click="closeSend">取 消</el-button>
            <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
    </div>
</template>
<style lang="less" scoped>
.inputValue {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 20px;

    &>div>div {
        margin-bottom: 10px;
    }
}

.default /deep/ .el-button {
    border-color: #303e9d;
    background-color: #303e9d;
}

.default /deep/ .el-button:hover {
    color: white;
    border-color: #DEEDF1;
    background-color: #DEEDF1;
}

/deep/ .el-button:hover {
    color: black;
    border-color: #DCDFE6;
    background-color: white;
}

span /deep/ .el-button:nth-child(2) {
    border-color: #303e9d;
    background-color: #303e9d;
}

span /deep/ .el-button:nth-child(2):hover {
    color: white;
    border-color: #DEEDF1;
    background-color: #DEEDF1;
}

/deep/ .el-input__inner:hover {
    border-color: #303e9d !important;
}

/deep/ .el-input__inner:focus {
    border-color: #303e9d !important;
}

/deep/ .selected {
    color: #303e9d !important;
}

/deep/ .active {
    color: #303e9d !important;
}

/deep/ .hover {
    color: #303e9d !important;
}

/deep/ .selected {
    color: #303e9d !important;
}

/deep/ .el-loading-text {
    color: #303e9d !important;
}

/deep/ .el-icon-loading {
    color: #303e9d !important;
}
</style>
